<template>
    <view :style="themeColor()">
        <view class="bg-[var(--page-bg-color)] min-h-[100vh]" v-if="orderData">
            <view class="pt-[30rpx] sidebar-margin payment-bottom">
                <!-- 配送方式 -->

                <view class="mb-[var(--top-m)] card-template   ">

                    <view class="card-template-item">
                        <view class="text-[32rpx] w-[150rpx] leading-[30rpx] text-[#303133]">选择员工</view>
                        <view
                            class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx] flex justify-end items-center"
                            @click="employeeRef.open(createData.employeeStr)">
                            <view class=" flex justify-end truncate">
                                <text v-if="createData.employeeStr && createData.employeeStr.length"
                                    class=" text-[32rpx]  ">
                                    {{ cartEmployeeText }}
                                </text>
                                <text class="text-[32rpx] text-gray-subtitle" v-else>请选择员工</text>
                            </view>
                            <text class="nc-iconfont nc-icon-youV6xx text-[var(--text-color-light9)] ml-[2rpx]"></text>
                        </view>
                    </view>
                </view>
                <view class="mb-[var(--top-m)] card-template p-[0] ">
                    <view class="py-[var(--pad-top-m)]">
                        <view class="mb-[20rpx] px-[var(--pad-sidebar-m)]" v-for="(item, index) in orderData.goods"
                            :key="index">
                            <view class="flex">
                                <u--image radius="var(--goods-rounded-big)" width="180rpx" height="180rpx"
                                    :src="img(item.picUrl)" model="aspectFill">
                                    <template #error>
                                        <image
                                            class="w-[180rpx] h-[180rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                            :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill">
                                        </image>
                                    </template>
                                </u--image>
                                <view class="flex flex-1 w-0 flex-col justify-between ml-[20rpx] py-[6rpx]">
                                    <view class="line-normal">
                                        <view class="truncate text-[#303133] font-bold text-[32rpx] leading-[32rpx]">
                                            <!-- <view class="brand-tag" v-if="item.spuType">
                                                {{ formatSpuType(item.spuType)
                                                }}
                                            </view> -->
                                            {{ item.spuName }}
                                        </view>
                                        <view class="mt-[14rpx] flex" v-if="item.properties">
                                            <text
                                                class="truncate text-[24rpx] text-[var(--text-color-light9)] leading-[28rpx]">{{
                                                    skuSpecFormat(item.properties)
                                                }}</text>
                                        </view>
                                        <view class="mt-[14rpx] flex">
                                            <text
                                                class="truncate text-[24rpx] text-[var(--text-color-light9)] leading-[28rpx]">销售订单:
                                                {{
                                                    item.no }}</text>
                                        </view>
                                        <view class="mt-[14rpx] flex">
                                            <text
                                                class="truncate text-[24rpx] text-[var(--text-color-light9)] leading-[28rpx]">销售员工:
                                                {{ countEmployeeText(item.employeeStr)
                                                }}</text>
                                        </view>
                                    </view>

                                    <view class="flex justify-between items-baseline">
                                        <view class="text-[var(--price-text-color)] flex items-baseline  price-font">
                                            <!-- <text class="text-[24rpx] font-500 mr-[4rpx]"> 可寄存数量: {{ item.units }}
                                            </text> -->


                                        </view>
                                        <view class="font-400 text-[32rpx] text-[#303133]">
                                            <text>x</text>
                                            <text>{{ item.count }}</text>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>



                </view>


                <view class="card-template">
                    <view class="title">寄存信息</view>
                    <view class="card-template-item" v-for="(item, index) in orderData.goods" :key="index">
                        <view class="text-[32rpx] w-[550rpx] leading-[30rpx] text-[#303133]">{{ item.spuName }}</view>
                        <view class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx]">
                            x{{ item.count }}
                        </view>
                    </view>
                </view>
            </view>
            <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" zIndex="10">
                <view class="flex-1 flex items-center justify-between pl-[30rpx] pr-[20rpx]">
                    <view class="flex items-baseline">
                        <text class="text-[32rpx] text-[#333] leading-[32rpx]">合计：</text>
                        <view class="inline-block">

                            <text class="text-[32rpx] font-500  price-font leading-[30rpx]">共</text>
                            <text
                                class="text-[44rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">{{
                                    itemsTimes
                                }}</text>
                            <text class="text-[32rpx] font-500  price-font leading-[30rpx]">件商品</text>
                        </view>
                    </view>
                    <button :loading="createLoading"
                        class="w-[250rpx]  h-[84rpx] font-500 text-[32rpx] leading-[84rpx] !text-[#fff] m-0  rounded-full  primary-btn-bg remove-border"
                        hover-class="none" @click="create">提交订单</button>
                </view>
            </u-tabbar>


        </view>


        <!-- 选择员工 -->
        <select-employee ref="employeeRef" @confirm="confirmSelectEmployee" />





    </view>
    <!-- 水印 -->
    <watermark></watermark>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

import { orderCreate } from '@/addon/deposit/api/order'
import { redirect, img } from '@/utils/common'
import { useSubscribeMessage } from '@/hooks/useSubscribeMessage'
import { onShow, onUnload } from '@dcloudio/uni-app'
import useCartStore from '@/addon/deposit/stores/cart'

const cartStore = useCartStore();

import { skuSpecFormat, formatSpuType } from '@/utils/formatting'
const createData: any = ref({
    no: computed(() => {
        return cartStore.orderId
    }),
    invoice: {},

    items: {},

    // ========== 员工 ==========
    employeeStr: [],
    // ========== 密码 ==========
    enalePassword: false, // 开启密码支付 true是
    password: undefined,//支付密码
})

const orderData: any = ref(null)
const employeeRef = ref()
const createLoading = ref(false)
const itemsTimes = computed(() => {
    let count = 0
    orderData.value.goods.forEach((ele) => {
        count += Number(ele.count)
    })
    return count
})
uni.getStorageSync('depositOrderCreateData') && Object.assign(createData.value, uni.getStorageSync('depositOrderCreateData'))
console.log(createData.value)
onShow(() => {
    const options = uni.getEnterOptionsSync();
    // scene 1038	从另一个小程序返回
    // #ifdef MP
    if (options.scene == 1038) {
        uni.$emit('scene', {
            scene: 1038
        })
        return
    }
    // #endif
    cartStore.getList();


})
onUnload(() => {
    uni.$off('scene')
})


/** 选择员工 */

const cartEmployeeText = computed(() => {
    let employeeText = '';
    createData.value.employeeStr.forEach((element, index) => {
        if (index == createData.value.employeeStr.length - 1) {
            employeeText += element.employeeName + ' ' + element.proportion + '%';
        } else {
            employeeText += element.employeeName + ' ' + element.proportion + '%' + '|';
        }
    });

    return employeeText;
});
const countEmployeeText = (arry: any) => {
    let employeeText = '';
    arry.forEach((element: any, index: any) => {
        if (index == arry.length - 1) {
            employeeText += element.employeeName + ' ' + element.proportion + '%';
        } else {
            employeeText += element.employeeName + ' ' + element.proportion + '%' + '|';
        }
    });
    return employeeText;
}



const confirmSelectEmployee = (employee: any) => {

    createData.value.employeeStr = employee


}
const confirmPassword = (password: any) => {
    createData.value.password = password
    create()
}
/**
 * 选择员工 end
 */

/**
 * 订单计算
 */
const calculate = () => {

    orderData.value = { goods: [] };

    if (cartStore.cartList && Object.values(cartStore.cartList).length) {
        Object.values(cartStore.cartList).forEach((item, index) => {
            Object.keys(item).forEach(v => {
                orderData.value.goods.push(item[v]);
            })

        })
    }

}

onMounted(() => {
    calculate()

})

let orderId = 0
/**
 * 订单创建
 */
const create = () => {
    if (!verify() || createLoading.value) return

    createLoading.value = true
    useSubscribeMessage().request('shop_order_pay,shop_order_delivery')
    let params = {
        reserveList: createData.value.items,
        employeeStr: createData.value.employeeStr, //员工
        no: createData.value.no,
        type: 1


    }

    orderCreate(params).then(async ({ data }) => {
        orderId = data.id
        // redirect({ url: '/addon/shop/pages/index', param: {}, mode: 'redirectTo' })

        redirect({ url: '/addon/deposit/pages/order/detail', param: { order_id: orderId }, mode: 'redirectTo' })

    }).catch(() => {
        createData.value.password = ""
        createLoading.value = false
    })
}

/**
 * 下单校验
 */
const verify = () => {

    let verify = true
    if (true) {
        if (cartEmployeeText.value == '') {

            employeeRef.value.open([])

            return false
        }


    }
    return verify
}








const confirmInvoice = (invoice: object) => {
    createData.value.invoice = invoice
}


</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

:deep(.u-tabbar) {
    .u-tabbar__content {

        .u-tabbar__content__item-wrapper {
            height: 120rpx !important;

        }
    }
}

.head-tab {
    .head-tab-item {
        .tab-image {
            left: 50%;
            transform: translateX(-50%);
        }

        &:nth-child(1).active {
            view {
                padding-right: 40rpx;
            }
        }

        &:nth-child(2) {
            .tab-image {
                width: 312rpx;
            }
        }

        &:nth-child(3).active {
            view {
                padding-left: 30rpx;
            }
        }

        &.active {
            view {
                font-weight: bold;
                color: var(--primary-color);
            }
        }

        .tab-img {
            left: 50%;
            transform: translateX(-50%);
        }

    }
}

:deep(.u-alert) {
    padding: 6rpx 16rpx !important;
    display: inline-block !important;
}

.alert-wrap {
    display: inline-block !important;

    :deep(.u-fade-enter-active) {
        display: inline-block !important;
    }
}

.text-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.line-normal {
    line-height: normal;
}

.bg-color {
    background: linear-gradient(94deg, var(--primary-help-color) 0%, var(--primary-color) 69%), var(--primary-color);
}

.payment-bottom {
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}
</style>
